package service

import (
	"context"
	"errors"
	"fmt"
	"patient-srv/basic/config"
	patient "patient-srv/basic/proto"
	"patient-srv/handler/model"
	"time"

	"gorm.io/gorm"
)

// CreatePrescriptionRequest 创建开药申请
func (s *PatientServiceServer) CreatePrescriptionRequest(ctx context.Context, req *patient.CreatePrescriptionRequestReq) (*patient.CreatePrescriptionResponse, error) {
	// 1. 验证患者信息
	var patientInfo model.Patient
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.PatientId, req.UserId).First(&patientInfo).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.CreatePrescriptionResponse{Message: "患者信息不存在"}, nil
		}
		return nil, err
	}

	// 2. 创建开药申请记录
	prescriptionReq := &model.PrescriptionRequest{
		UserID:               req.UserId,
		PatientID:            req.PatientId,
		SymptomDescription:   req.SymptomDescription,
		PrescriptionImageUrl: req.PrescriptionImageUrl,
		Status:               1, // 待选择医生
		TotalAmount:          0,
		CreatedAt:            time.Now(),
		UpdatedAt:            time.Now(),
	}

	if err := config.GlobalDB.Create(prescriptionReq).Error; err != nil {
		return nil, err
	}

	return &patient.CreatePrescriptionResponse{
		Message:               "创建成功",
		PrescriptionRequestId: prescriptionReq.ID,
	}, nil
}

// GetPrescriptionRequestDetail 获取开药申请详情
func (s *PatientServiceServer) GetPrescriptionRequestDetail(ctx context.Context, req *patient.GetPrescriptionRequestDetailReq) (*patient.PrescriptionRequestDetailResponse, error) {
	var prescriptionReq model.PrescriptionRequest
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.PrescriptionRequestId, req.UserId).First(&prescriptionReq).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.PrescriptionRequestDetailResponse{Message: "开药申请不存在"}, nil
		}
		return nil, err
	}

	// 获取患者信息
	var patientInfo model.Patient
	config.GlobalDB.Where("id = ?", prescriptionReq.PatientID).First(&patientInfo)

	// 获取药品列表
	var medicines []model.PrescriptionMedicine
	config.GlobalDB.Where("prescription_request_id = ?", prescriptionReq.ID).Find(&medicines)

	var medicineItems []*patient.MedicineItem
	for _, med := range medicines {
		medicineItems = append(medicineItems, &patient.MedicineItem{
			MedicineId:   med.MedicineID,
			MedicineName: med.MedicineName,
			Quantity:     int32(med.Quantity),
			Price:        med.Price,
			Dosage:       med.Dosage,
		})
	}

	// TODO: 调用 doctor-srv 获取医生信息
	doctorName := ""
	if prescriptionReq.DoctorID > 0 {
		doctorName = fmt.Sprintf("医生%d", prescriptionReq.DoctorID)
	}

	return &patient.PrescriptionRequestDetailResponse{
		Message: "获取成功",
		PrescriptionRequest: &patient.PrescriptionRequestInfo{
			Id:                   prescriptionReq.ID,
			UserId:               prescriptionReq.UserID,
			PatientId:            prescriptionReq.PatientID,
			PatientName:          patientInfo.Name,
			DoctorId:             prescriptionReq.DoctorID,
			DoctorName:           doctorName,
			SymptomDescription:   prescriptionReq.SymptomDescription,
			PrescriptionImageUrl: prescriptionReq.PrescriptionImageUrl,
			Medicines:            medicineItems,
			Status:               int32(prescriptionReq.Status),
			TotalAmount:          prescriptionReq.TotalAmount,
			CreatedAt:            prescriptionReq.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:            prescriptionReq.UpdatedAt.Format("2006-01-02 15:04:05"),
		},
	}, nil
}

// GetPrescriptionRequestList 获取开药申请列表
func (s *PatientServiceServer) GetPrescriptionRequestList(ctx context.Context, req *patient.GetPrescriptionRequestListReq) (*patient.PrescriptionRequestListResponse, error) {
	var prescriptionReqs []model.PrescriptionRequest
	query := config.GlobalDB.Where("user_id = ?", req.UserId)

	// 如果指定状态，添加条件
	if req.Status > 0 {
		query = query.Where("status = ?", req.Status)
	}

	// 分页
	page := req.Page
	pageSize := req.PageSize
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 10
	}
	offset := (page - 1) * pageSize

	// 查询总数
	var total int64
	query.Model(&model.PrescriptionRequest{}).Count(&total)

	// 查询列表
	err := query.Order("id DESC").Offset(int(offset)).Limit(int(pageSize)).Find(&prescriptionReqs).Error
	if err != nil {
		return nil, err
	}

	var result []*patient.PrescriptionRequestInfo
	for _, presReq := range prescriptionReqs {
		// 获取患者信息
		var patientInfo model.Patient
		config.GlobalDB.Where("id = ?", presReq.PatientID).First(&patientInfo)

		// 获取药品列表
		var medicines []model.PrescriptionMedicine
		config.GlobalDB.Where("prescription_request_id = ?", presReq.ID).Find(&medicines)

		var medicineItems []*patient.MedicineItem
		for _, med := range medicines {
			medicineItems = append(medicineItems, &patient.MedicineItem{
				MedicineId:   med.MedicineID,
				MedicineName: med.MedicineName,
				Quantity:     int32(med.Quantity),
				Price:        med.Price,
				Dosage:       med.Dosage,
			})
		}

		doctorName := ""
		if presReq.DoctorID > 0 {
			doctorName = fmt.Sprintf("医生%d", presReq.DoctorID)
		}

		result = append(result, &patient.PrescriptionRequestInfo{
			Id:                   presReq.ID,
			UserId:               presReq.UserID,
			PatientId:            presReq.PatientID,
			PatientName:          patientInfo.Name,
			DoctorId:             presReq.DoctorID,
			DoctorName:           doctorName,
			SymptomDescription:   presReq.SymptomDescription,
			PrescriptionImageUrl: presReq.PrescriptionImageUrl,
			Medicines:            medicineItems,
			Status:               int32(presReq.Status),
			TotalAmount:          presReq.TotalAmount,
			CreatedAt:            presReq.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:            presReq.UpdatedAt.Format("2006-01-02 15:04:05"),
		})
	}

	return &patient.PrescriptionRequestListResponse{
		Message:              "获取成功",
		PrescriptionRequests: result,
		Total:                int32(total),
	}, nil
}

// AddMedicineToPrescription 添加药品到处方
func (s *PatientServiceServer) AddMedicineToPrescription(ctx context.Context, req *patient.AddMedicineToPrescriptionReq) (*patient.BaseResponse, error) {
	// 1. 验证开药申请
	var prescriptionReq model.PrescriptionRequest
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.PrescriptionRequestId, req.UserId).First(&prescriptionReq).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.BaseResponse{Message: "开药申请不存在"}, nil
		}
		return nil, err
	}

	// 2. TODO: 调用药品服务获取药品信息和价格
	medicineName := fmt.Sprintf("药品%d", req.MedicineId)
	price := 10.0 // 暂时写死，实际应该从药品服务获取

	// 3. 检查药品是否已添加
	var existingMedicine model.PrescriptionMedicine
	err = config.GlobalDB.Where("prescription_request_id = ? AND medicine_id = ?", req.PrescriptionRequestId, req.MedicineId).First(&existingMedicine).Error
	if err == nil {
		return &patient.BaseResponse{Message: "该药品已添加"}, nil
	}

	// 4. 添加药品
	medicine := &model.PrescriptionMedicine{
		PrescriptionRequestID: req.PrescriptionRequestId,
		MedicineID:            req.MedicineId,
		MedicineName:          medicineName,
		Quantity:              int(req.Quantity),
		Price:                 price,
		Dosage:                req.Dosage,
		CreatedAt:             time.Now(),
	}

	if err := config.GlobalDB.Create(medicine).Error; err != nil {
		return nil, err
	}

	// 5. 更新总金额
	var totalAmount float64
	config.GlobalDB.Model(&model.PrescriptionMedicine{}).
		Where("prescription_request_id = ?", req.PrescriptionRequestId).
		Select("SUM(price * quantity)").
		Scan(&totalAmount)

	config.GlobalDB.Model(&prescriptionReq).Updates(map[string]interface{}{
		"total_amount": totalAmount,
		"updated_at":   time.Now(),
	})

	return &patient.BaseResponse{Message: "添加成功"}, nil
}

// RemoveMedicineFromPrescription 从处方移除药品
func (s *PatientServiceServer) RemoveMedicineFromPrescription(ctx context.Context, req *patient.RemoveMedicineFromPrescriptionReq) (*patient.BaseResponse, error) {
	// 1. 验证开药申请
	var prescriptionReq model.PrescriptionRequest
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.PrescriptionRequestId, req.UserId).First(&prescriptionReq).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.BaseResponse{Message: "开药申请不存在"}, nil
		}
		return nil, err
	}

	// 2. 删除药品
	err = config.GlobalDB.Where("prescription_request_id = ? AND medicine_id = ?", req.PrescriptionRequestId, req.MedicineId).
		Delete(&model.PrescriptionMedicine{}).Error
	if err != nil {
		return nil, err
	}

	// 3. 更新总金额
	var totalAmount float64
	config.GlobalDB.Model(&model.PrescriptionMedicine{}).
		Where("prescription_request_id = ?", req.PrescriptionRequestId).
		Select("SUM(price * quantity)").
		Scan(&totalAmount)

	config.GlobalDB.Model(&prescriptionReq).Updates(map[string]interface{}{
		"total_amount": totalAmount,
		"updated_at":   time.Now(),
	})

	return &patient.BaseResponse{Message: "删除成功"}, nil
}

// SelectPrescriptionDoctor 选择开药医生
func (s *PatientServiceServer) SelectPrescriptionDoctor(ctx context.Context, req *patient.SelectPrescriptionDoctorReq) (*patient.BaseResponse, error) {
	// 1. 验证开药申请
	var prescriptionReq model.PrescriptionRequest
	err := config.GlobalDB.Where("id = ? AND user_id = ?", req.PrescriptionRequestId, req.UserId).First(&prescriptionReq).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return &patient.BaseResponse{Message: "开药申请不存在"}, nil
		}
		return nil, err
	}

	// 2. TODO: 调用 doctor-srv 验证医生信息

	// 3. 更新医生ID和状态
	if err := config.GlobalDB.Model(&prescriptionReq).Updates(map[string]interface{}{
		"doctor_id":  req.DoctorId,
		"status":     2, // 待支付
		"updated_at": time.Now(),
	}).Error; err != nil {
		return nil, err
	}

	// 4. 创建订单
	orderNo := model.GenerateOrderNo(3) // 3表示开药订单
	order := &model.Order{
		OrderNo:   orderNo,
		UserID:    req.UserId,
		OrderType: 3, // 开药
		Status:    1, // 待支付
		Amount:    prescriptionReq.TotalAmount,
		RelatedID: prescriptionReq.ID,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}

	if err := config.GlobalDB.Create(order).Error; err != nil {
		return nil, err
	}

	// 5. 更新开药申请的订单ID
	config.GlobalDB.Model(&prescriptionReq).Update("order_id", order.ID)

	return &patient.BaseResponse{Message: "选择成功"}, nil
}
